//
//  SouthChinaAppDelegate.m
//  SouthChina
//
//  Created by Mr.Y on 14-10-8.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "SouthChinaAppDelegate.h"
#import "AddressBookViewController.h"
#import "LaunchImageTransition.h"
#import "TabbarViewController.h"
#import "Reachability.h"
#import <BaiduMapAPI/BMapKit.h>
#import "ContactDao.h"

BMKMapManager* _mapManager;

@interface SouthChinaAppDelegate ()<BMKGeneralDelegate>
{
    
}
@end

@implementation SouthChinaAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self initBaseData];
    NSLog(@"XXXXXXXXXXXXXXXdidFinishLaunchingWithOptions");
    LaunchImageTransition * information = [[LaunchImageTransition alloc] init];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:information];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"uaY91GiTS8Dqayl8apjroBf0" generalDelegate:self]; //com.chinacreator.ccmp
    if (!ret) {
        NSLog(@"百度地图启动失败!");
    }
    
    self.needRefrsh = NO;
    self.mqttState = MQTT_NO_CONNECT;
    //把之前的通知全部清除
    [application cancelAllLocalNotifications];
    
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        // iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [application registerForRemoteNotifications];
    }
    else
    {
        // iOS < 8 Notifications
        [application registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }
    application.applicationIconBadgeNumber =0;
    
    return YES;
}

- (void)initBaseData{
    
    DE.serverName = SERVERIP;
    DE.serverProjectName = SERVERNAME;
    DE.serverPort = SERVERPORT;
    DE.msgServerName = MQIP;
    DE.msgServerPort = MQPORT;
    DE.serverUri = SERVERURI;
    
    DE.appId=APPLICATION_ID;
    DE.msgBroadcastName = MSGBROADCASTNAME;
    DE.fileEngineeUrl = FILENGINEERURL;
    
    // 要使用百度地图，请先启动BaiduMapManager
    /*
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"gR1vYGaps9vhYi5LO9WpEzlk" generalDelegate:self];
    if (!ret) {
        NSLog(@"百度地图启动失败!");
    }
    */
}


- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}


//获取deviceToken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceTokenn
{
    NSLog(@"deviceToken:%@",deviceTokenn);
    NSString* device_token = [NSString stringWithFormat:@"%@",deviceTokenn];
    device_token =[device_token stringByReplacingOccurrencesOfString:@" " withString:@""];
    device_token =[device_token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    device_token =[device_token stringByReplacingOccurrencesOfString:@">" withString:@""];
    DE.deviceToken = device_token;
    NSLog(@"deviceToken == %@",DE.deviceToken);
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    application.applicationIconBadgeNumber =0;
    NSString *fileUserId = [DE getGlobalVar:LOGIN_USER_ID];
    if (fileUserId && fileUserId.length>0 && [Reachability isNetConnect]) {
        NSLog(@"applicationDidBecomeActiveADFAFASEDAD");
        //更新数据库版本判断
        NSString *dataVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],DATABASEVERSION]];
        NSLog(@"当前在用的数据库版本为databasevision.......%@",dataVersion);
        //是否为当前版本号，不是的话，需要更新数据库
        if (![dataVersion isEqualToString:CURDATABASEVERSION])
        {
            //需要更新的话，就不加载重载check in啦
            NSLog(@"发现有新的数据库版本了，需要更新，重新登录");
        }
        else
        {
             NSLog(@"XZZZZZZZZZZZZZZZZZZZZZZZZZ");
            [DE reload];
        }

    }
    //添加网络监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];//可以以多种形式初始化
    [self.hostReach startNotifier];
}

//网络连接改变
- (void) reachabilityChanged: (NSNotification* )note{
//    [self performSelector:@selector(scale_2) withObject:nil afterDelay:5.0f];
    Reachability *curr = [note object];
    NetworkStatus state = [curr currentReachabilityStatus];
    if (state ==NotReachable) {
        self.mqttState = MQTT_NO_CONNECT;
    }
    else{
        NSString *fileUserId = [DE getGlobalVar:LOGIN_USER_ID];
        if (fileUserId && fileUserId.length>0 && [Reachability isNetConnect] && self.mqttState!=MQTT_CONNECTTED)
        {
            //NSLog(@"-------@@@reconnectFunction-!!!-@@checkin@@----");
            NSLog(@"YYYYYYYYYYYYYYYYYYYYYYYYYYYY");
            //更新数据库版本判断
            NSString *dataVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],DATABASEVERSION]];
            NSLog(@"网络连接改变,当前在用的数据库版本为databasevision.......%@",dataVersion);
            //是否为当前版本号，不是的话，需要更新数据库
            if (![dataVersion isEqualToString:CURDATABASEVERSION])
            {
                //需要更新的话，就不加载重载check in啦
                NSLog(@"网络连接改变,发现有新的数据库版本了，需要更新，重新登录");
            }
            else
              [DE reload];
        }
    }

}


//收到远程的apns消息，说明mqtt没有及时响应，可能已经掉线，则进行checkin操作
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"-------@@@didReceiveRemoteNotification-!!NO  No  no!-@@----");
    NSString *fileUserId = [DE getGlobalVar:LOGIN_USER_ID];
    if (fileUserId && fileUserId.length>0 && [Reachability isNetConnect])
    {
        NSLog(@"-------@@@didReceiveRemoteNotification-!!!-@@checkin@@----");
        [DE reload];
    }
}
-(void)scale_2
{
    //NSLog(@"-------@@@reachabilityChanged--@ NET----");
    
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"applicationWillResignActive--");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"applicationDidEnterBackground--");
    [application cancelAllLocalNotifications];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    NSLog(@"applicationWillEnterForeground--");
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"applicationWillTerminate--");
    [application cancelAllLocalNotifications];

}


@end
